package top.juc.plugin.idea.openfeignx.util;

import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;

/**
 * The type File utils.
 *
 * @author yanglin
 */
public final class FileUtils {

    /**
     *
     * 刷新当前IDEA打开的文件
     * @param project
     * @return
     */
    public static void refreshCurrentOpenFile(Project project) {
        // 获取当前打开的文件列表
        VirtualFile[] openFiles = FileEditorManager.getInstance(project).getOpenFiles();
        if(openFiles == null || openFiles.length == 0) {
           return;
        }
        PsiManager psiManager = PsiManager.getInstance(project);
        for (VirtualFile file : openFiles) {
            PsiFile psiFile = psiManager.findFile(file);
            if (psiFile == null) {
                continue;
            }
            PsiClass psiClass = findClassInPsiFile(psiFile);
            if (psiClass == null) {
                continue;
            }
            NavigationUtil.collectRelatedItems(psiClass, null);
        }
    }

    private static PsiClass findClassInPsiFile(PsiFile psiFile) {
        // 遍历 PSI 文件中的所有元素，查找 PsiClass
        for (PsiElement element : psiFile.getChildren()) {
            if (element instanceof PsiClass) {
                return (PsiClass) element;
            }
        }
        return null;
    }

}
